<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./js/axios.min.js"></script>
    <script src="./js/api.js"></script>
  </head>
  <body>
    <div id="item-div"></div>
    <script>
      /**  
         * 
         详情    在商品列表生成的时候 

         <a href="item.html?pid=${pObj.pid}">      </a>

         通过url 传递过去了 商品的id  ？pid=111  

        获取 url  搜索字段    pid   
         
         调用 根据商品id 获取商品详情的接口 -》  展示到  div中   

         给加入购物车添加点击事件，点击的时候 获取输入框（数量）的值，发起 修改请求
         * 
         *  */

      //  ?pid=499854&aa=12
      console.log(location.search);

      //   URLSearchParams 构造函数 能?pid=499854&aa=12-》对象
      let obj = new URLSearchParams(location.search);
      console.log(obj.get("pid"));
      let pid = obj.get("pid");

      //   productDetailAPI
      //   接口参数：
      // id  商品的id
      axios
        .get(productDetailAPI, {
          params: { id: pid },
        })
        .then((res) => {
          let { data } = res;
          console.log(data);
          //商品详情数据
          let pObj = data.data;
          let html = `
            <h1>${pObj.pname}</h1>

            <p>${pObj.pprice}</p>
            <img src="${pObj.pimg}" alt="" />

            <input type="number" name="" id=""  value='1' class="pnum-ipt"/>
            <input type="button" value="加入购物车"  class="cart-add" />

            <p>${pObj.pdesc}</p>
          `;
          let itemDiv = document.querySelector("#item-div");
          itemDiv.innerHTML = html; //  item div 才有内容  才有加入购物车按钮
          let cartAdd = document.querySelector(".cart-add");
          console.log(cartAdd); //null
          cartAdd.onclick = async function () {
            console.log(111);
            //uid  用户id
            // pid  商品id
            // pnum  要添加的商品数量
            let uid = localStorage.getItem("uid");
            let pnumIpt = document.querySelector(".pnum-ipt");
            let pnum = pnumIpt.value;
            let params = { uid, pid, pnum };
            console.log(params);
            let { data } = await axios.get(CartAddAPI, { params });
            console.log(data);
          };
        });

      // 必须等页面有 了按钮 ，才能去获取
      let cartAdd = document.querySelector(".cart-add");
      console.log(cartAdd); //null
    </script>
  </body>
</html>
